package com.baicaoyuan.web.repository;


import com.baicaoyuan.web.model.UserDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;

/**
 * 功能描述：用户模型
 *
 * @author 罗富祥
 * 创建时间： 2018/1/4
 * 版权：
 */
@Repository
public interface UserRepository extends JpaRepository<UserDO, Long> {

    /**
     * 根据手机号获取用户信息
     *
     * @param telephone
     * @return
     */
    UserDO findByTelephone(String telephone);

    /**
     * 根据邀请码获取用户
     *
     * @param invitationCode
     * @return
     */
    UserDO findByInvitationCode(String invitationCode);

    Integer countAllByStatusIsNotAndTelephoneLikeAndCategoryLike(String status, String telephone, String category);

    @Query(value = "select * from t_user where status != 9 and telephone like ?1 and category like ?2 order by id desc Limit ?3,?4", nativeQuery = true)
    List<UserDO> getUsers(String telephone, String category, Integer page, Integer size);

    List<UserDO> findByStatusAndType(String status, Integer type);

    List<UserDO> findByUserDirectId(Long userDirectId);

    List<UserDO> findByUserDirectIdAndType(Long userDirectId, Integer type);

    List<UserDO> findByUserIndirectIdAndType(Long userIndirectId, Integer type);

    List<UserDO> findByStatusAndCategory(String status, String category);

    Long countByUserDirectId(Long userDirectId);

    @Transactional
    @Modifying
    @Query(value = "update t_user set status = ?2 where id = ?1", nativeQuery = true)
    Integer updateStatus(Long id, String status);

    @Transactional
    @Modifying
    @Query(value = "update t_user set token = ?2 where id = ?1", nativeQuery = true)
    Integer updateToken(Long id, String token);

    @Transactional
    @Modifying
    @Query(value = "update t_user set type = ?2 where id = ?1", nativeQuery = true)
    Integer updateType(Long id, Integer type);

    @Transactional
    @Modifying
    @Query(value = "update t_user set  contribution_value_total = contribution_value_total +?2 where id = ?1", nativeQuery = true)
    Integer plusContribution(Long userId, BigDecimal contributionValue);

    @Transactional
    @Modifying
    @Query(value = "update t_user set  category = ?2 where id = ?1", nativeQuery = true)
    Integer setCategory(Long userId, String category);

    @Transactional
    @Modifying
    @Query(value = "update t_user set  score_total = score_total +?2 where id = ?1", nativeQuery = true)
    Integer plusScore(Long userId, BigDecimal score);


}
